﻿using System;
using System.Linq;
using c = NHibernate.Cfg;

namespace OrmSmackdown.LinqToNHibernate
{
    public class Crud : ICrud
    {
        OrmSmackdownContext _ctx;

        public Crud()
        {
            c.Configuration _configuration = new c.Configuration();
            _configuration.AddAssembly("OrmSmackdown");
            var sessionFactory = _configuration.BuildSessionFactory();
            var session = sessionFactory.OpenSession();
            _ctx = new OrmSmackdownContext(session);
        }

        public int Create(string firstName, string lastName, string email)
        {
            var contact1 = new NHibernate.Contact { FirstName = firstName, LastName = lastName, Email = email};

            _ctx.Session.Save(contact1);
            _ctx.Session.Flush();

            return contact1.PersonId;
        }

        public IPerson Read(int id)
        {
            return _ctx.Contacts.Where(p=>p.PersonId == id).FirstOrDefault() as IPerson;
        }

        public void Update(int id, string firstName, string lastName, string email)
        {
            var person = _ctx.Contacts.Where(p=>p.PersonId == id).FirstOrDefault();
            person.FirstName = firstName;
            person.LastName = lastName;
            person.Email = email;

            _ctx.Session.Save(person);
            _ctx.Session.Flush();
        }

        public void Delete(int id)
        {
            var person = _ctx.Contacts.Where(p => p.PersonId == id).FirstOrDefault();

            _ctx.Session.Delete(person);
            _ctx.Session.Flush();
        }


        public void Dispose()
        {
            _ctx.Dispose();

        }
    }
}
